'''
Created on 2011-10-17

@author: me
'''
from twisted.internet import protocol, reactor, defer 
from twisted.protocols import basic 
from MySQLdb import *

class DBQueryProtocol(basic.LineReceiver): 
    def lineReceived(self, user): 
        self.factory.getUser(user)
            .addErrback(lambda _: 'Internal error in server')
            .addCallback(lambda m: (self.transport.write(m + "\r\n"),
                                    self.transport.loseConnection()))

class DBQueryFactory(protocol.ServerFactory): 
    protocol = DBQueryProtocol

    def _dataFromDb(self, username): 
        conn = Connection('localhost', 'root', '111111', 'userdata') 
        cur = conn.cursor() 
        sql = 'select status from users where user like \%%s\%' % (username,) 
        cur.execute(sql) 
        try: 
            result = cur.fetchone()[1] 
        except: 
            result = 'No such user'

        return result

def getUser(self, user): 
    return defer.succeed(self._datafromDb(user))

reactor.listenTCP(1079, DBQueryFactory()) 
reactor.run()
    
